package com.example.blog.service;

import com.example.blog.dao.CommentRepository;
import com.example.blog.pojo.Comment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService{
    @Autowired
    private CommentRepository commentRepository;

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        Sort sort =Sort.by(Sort.Direction.DESC,"createTime");
       List<Comment> comments = commentRepository.myfindByBlogId(blogId,sort);

        return eachComment(comments);
    }
    private List<Comment> eachComment(List<Comment> comments){
        List<Comment> commentsView = new ArrayList<>();
        for(Comment comment : comments){

            Comment c = new Comment();
            BeanUtils.copyProperties(comment,c);
            commentsView.add(c);
        }
        comBineChildren(commentsView);
        return commentsView;
    }
    private List<Comment> tempReplys = new ArrayList<>();
    private void comBineChildren(List<Comment> comments){
        for(Comment comment: comments){
            List<Comment> replys1 = comment.getReplyComment();
            for(Comment reply1 : replys1){
                recursicely(reply1);

            }
            comment.setReplyComment(tempReplys);
            tempReplys = new ArrayList<>();
        }

    }

    private void recursicely(Comment comment){
        tempReplys.add(comment);
        if(comment.getReplyComment().size() > 0){
            List<Comment> replys = comment.getReplyComment();
            for(Comment  reply :replys){
                tempReplys.add(reply);
                if(reply.getReplyComment().size()>0){
                    recursicely(reply);
                }
            }
        }
    }
    @Override
    public Comment saveComment(Comment comment) {
       Long parentCommentId = comment.getParentComment().getId();
       if(parentCommentId != -1){
           comment.setParentComment(commentRepository.getOne(parentCommentId));

       }else {
           comment.setParentComment(null);
       }
       comment.setCreateTime(new Date());

        return commentRepository.save(comment);
    }
}
